package ru.develbureau.server;

import javax.persistence.EntityManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.develbureau.server.model.ClientRequestEntity;
import ru.develbureau.server.persistence.EMF;

import java.util.Date;
import java.util.Map;
import java.util.logging.Logger;
import static ru.develbureau.server.model.ModelValidator.validateClientRequest;
public class SaveRequestServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(SaveRequestServlet.class.getName());

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response){
		EntityManager em = null;
		ClientRequestEntity clientRequest = new ClientRequestEntity();
			clientRequest.setName(request.getParameter("name"));
			clientRequest.setPhone(request.getParameter("phone"));
			clientRequest.setSource(request.getParameter("source"));
			clientRequest.setTarget(request.getParameter("target"));
			clientRequest.setTime(request.getParameter("time"));
			clientRequest.setPublishDate(new Date());
			log.info("doPost -> " + clientRequest.toString());
		
		Map<String, String> errors = validateClientRequest(clientRequest);
		RequestDispatcher requestDispatcher = null;
		if(errors.size()>0){
			request.setAttribute("errors", errors);
			request.setAttribute("clientRequest", clientRequest);
			log.warning("ClientRequest has errors["+errors+"]");
			requestDispatcher = request.getRequestDispatcher("/index.jsp");		
		}
		else{
			em = EMF.get().createEntityManager();
			em.persist(clientRequest);
			request.setAttribute("name", clientRequest.getName());
			requestDispatcher = request.getRequestDispatcher("/result.jsp");
		}
		
		try{
			requestDispatcher.forward(request, response);
		}catch(Exception e){
			log.throwing("Error while dispatching request", e.getMessage(), e);
		}
		finally{
			EMF.close(em);
		}
	}
}
